// pages/cart/cart.js
import { getCartListApi, updateCartCheckApi, updateCheckAllApi, delCartApi, updateCartCountApi } from '../../api/cart';
import { throttle, debounce } from '../../utils/tools';

const app = getApp();
/*
  购物车的状态：
    1. 未登录状态
      空、提示去登录
    2. 登录了，但是没有数据
      空，提示去添加购物车
    3. 登录了，有数据
*/

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartList: [],
    totalPrice: 0,
    totalCount: 0,
    isCheckAll: false, // 全选&全不选
    isLogin: false
  },
  onShow() {
    const token = app.globalData.token;
    this.setData({
      isLogin: !!token
    });
    if (!token) return;
    this.getCartList();
  },
  // 获取购物车列表
  getCartList: async function() {
    const cartList = await getCartListApi();

    const totalPrice = cartList.reduce((p, c) => {
      return p + (c.isChecked ? c.price * c.count : 0)
    }, 0);

    const totalCount = cartList.reduce((p, c) => {
      return p + (c.isChecked ? c.count : 0)
    }, 0);

    const isCheckAll = cartList.every(cart => cart.isChecked)

    this.setData({
      cartList,
      totalPrice,
      totalCount,
      isCheckAll
    })
  },
  // 单选
  updateCartCheck: throttle(async function(e) {
    const { goodsid, ischecked } = e.currentTarget.dataset;
    // await updateCartCheckApi(goodsid, ischecked === 1 ? 0 : 1);
    await updateCartCheckApi(goodsid, 1 - ischecked);
    // 重新获取数据展示
    this.getCartList();
  }, 500),
  // 全选&全不选
  updateCheckAll: throttle(async function() {
    await updateCheckAllApi(this.data.isCheckAll ? 0 : 1)
    // updateCheckAllApi(+!this.data.isCheckAll)
    this.getCartList();
  }, 500),
  // 删除
  delCart(e) {
    wx.showModal({
      title: '删除',
      content: '您确认要删除当前商品吗?',
      success: async (res) => {
        if (res.confirm) {
          // console.log('用户点击确定')
          await delCartApi(e.currentTarget.dataset.goodsid);
          this.getCartList();
        }
      }
    })
  },
  // 更新商品数量
  updateCartCount: debounce(async function (e) {
    const { goodsid, count } = e.currentTarget.dataset;
    const newCount = e.detail;
    await updateCartCountApi(goodsid, newCount - count);
    this.getCartList();
  }, 500),
  // 去订单页面
  goOrder() {
    wx.navigateTo({
      url: '/pages/order/detail/detail',
    })
  },
})